package lesson.ch5;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class IndexDao implements IIndexDao {

	private String indFileName;

	public static void main(String[] args) throws IOException {
		IndexDao d = new IndexDao();
		d.setIndFileName("D:\\workspace\\mavenpro1\\ind.txt");
		Map<String, ArrayList<String>> map = d.load();
		for (String key : map.keySet()) {
			for (String value : map.get(key)) {
				System.out.println(key + " -- " + value);
			}
		}

	}

	public Map<String, ArrayList<String>> load() {
		Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(indFileName));
		} catch (FileNotFoundException e) {

			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String line = null;
		try {
			while ((line = br.readLine()) != null) {
				String[] strs = line.split("/");
				String key = strs[0];
				String value = strs[1];
				if (map.containsKey(key)) {
					map.get(key).add(value);
				} else {
					ArrayList<String> astrlist = new ArrayList<String>();
					astrlist.add(value);
					map.put(key, astrlist);

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public void unload(Map<String, ArrayList<String>> map) {
		File outFile = new File(indFileName);
		if (outFile.isFile() && outFile.exists())
			outFile.delete();
		FileWriter fw = null;
		try {
			outFile.createNewFile();

			fw = new FileWriter(outFile);
			for (String key : map.keySet()) {
				for (String value : map.get(key)) {
					fw.write(key + "/" + value + "\n");
				}
			}
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String getIndFileName() {
		return indFileName;
	}

	public void setIndFileName(String indFileName) {
		this.indFileName = indFileName;
	}

}
